<?php
namespace app\api\controller;

use app\BaseController;
use think\facade\Db;
use app\common\service\JwtService;
use think\facade\Validate;

class Auth extends BaseController
{
    protected $jwtService;

    public function __construct()
    {
        $this->jwtService = new JwtService();
    }

    /**
     * 用户注册
     * POST /api/auth/register
     */
    public function register()
    {
        $validate = Validate::rule([
            'phone' => 'require|length:11|number',
            'password' => 'require|min:6'
        ]);

        if (!$validate->check($this->request->post())) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        $data = $this->request->post();
        $phone = $data['phone'];

        // 检查手机号是否已存在
        $exists = Db::name('user')->where('phone', $phone)->find();
        if ($exists) {
            return json(['code' => 400, 'msg' => '手机号已注册']);
        }

        // 密码加密
        $hashedPassword = password_hash($data['password'], PASSWORD_BCRYPT);

        $userId = Db::name('user')->insertGetId([
            'phone' => $phone,
            'password' => $hashedPassword,
            'nickname' => '用户' . substr($phone, -4),
            'create_time' => date('Y-m-d H:i:s')
        ]);

        // 生成 Token
        $token = $this->jwtService->generateToken($userId);

        return json([
            'code' => 200,
            'msg' => '注册成功',
            'data' => [
                'token' => $token,
                'user' => [
                    'id' => $userId,
                    'phone' => $phone,
                    'nickname' => '用户' . substr($phone, -4)
                ]
            ]
        ]);
    }

    /**
     * 用户登录
     * POST /api/auth/login
     */
    public function login()
    {
        $validate = Validate::rule([
            'phone' => 'require|length:11|number',
            'password' => 'require|min:6'
        ]);

        if (!$validate->check($this->request->post())) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        $data = $this->request->post();
        $user = Db::name('user')->where('phone', $data['phone'])->find();

        if (!$user || !password_verify($data['password'], $user['password'])) {
            return json(['code' => 400, 'msg' => '手机号或密码错误']);
        }

        $token = $this->jwtService->generateToken((int)$user['id']);

        return json([
            'code' => 200,
            'msg' => '登录成功',
            'data' => [
                'token' => $token,
                'user' => [
                    'id' => $user['id'],
                    'phone' => $user['phone'],
                    'nickname' => $user['nickname'],
                    'avatar' => $user['avatar']
                ]
            ]
        ]);
    }
}